<?php
include_once(dirname(__FILE__) . "/../inc/common.php");
$method = isset($_GET["method"]) ? $_GET["method"] : "";

$flowClass = new tally_flow();

$excludeTagIds = explode(",", "38");
$excludeCategoryIds = explode(",", "31,28,52,20");
$excludeMarks = explode(",", "vip");

$tallyTagClass = new tally_tag();
$excludeTags = $tallyTagClass->findTagByIds($userId, $excludeTagIds);

$tallyFlowTypeClass = new tally_flowType();
$excludeCategories = $tallyFlowTypeClass->findFlowTypeByIds($userId, $excludeCategoryIds);

function _array_column($list, $element)
{
    if (!isset($list) || !is_array($list) || empty($list)) {
        return array();
    }
    if (!isset($element) || empty($element)) {
        return array();
    }
    $j = 0;
    $result = array();
    for ($i = 0; $i < count($list); $i++) {
        if (isset($list [$i] [$element])) {
            $result [$j] = $list [$i] [$element];
            $j++;
        } else {
            return array();
        }
    }
    return $result;
}

if ($method == "listQry") {
    // 所时间段每月收入与支出
    $dateFrom = isset($_POST["dateFrom"]) && $_POST["dateFrom"] ? strtotime($_POST["dateFrom"]) : strtotime("1970-01-01");
    $dateTo = isset($_POST["dateTo"]) && $_POST["dateTo"] ? strtotime($_POST["dateTo"]) : time();
    $tagIds = isset($_POST["tagId"]) ? trim($_POST["tagId"], ",") : "";
    $categoryId = isset($_POST["categoryId"]) ? $_POST["categoryId"] : null;
    $excludeMarks = isset($_POST["excludeMarks"]) ? trim($_POST["excludeMarks"], ",") : "";

    $startTime = $dateFrom;
    $endTime = strtotime(date('Y-m-' . date('t', $startTime) . ' 23:59:59', $startTime));
    $categories = array();
    $outList = array();
    while ($startTime < $dateTo) {
        $thisMonthOut = $flowClass->getCountByTimeRangeExcludeFilter($userId,
            tally_flow::$INOUT_EXPENSE, $startTime, $endTime, $tagIds, $categoryId, $excludeMarks);
        $month = date("n月", $startTime);
        $categories[] = $month;
        $outList[] = array(
            "month" => $month,
            "start" => date("Y-m-d H:i:s", $startTime),
            "end" => date("Y-m-d H:i:s", $endTime),
            "sumOut" => abs($thisMonthOut)
        );

        $startTime = $endTime + 1;
        $endTime = strtotime(date('Y-m-' . date('t', $startTime) . ' 23:59:59', $startTime));
    }

    ?>
    <!--begin:数据列表-------------------------------------------------------------------------------------------------->
    <table id="listtb" class="listtable" cellpadding="0" cellspacing="1">
        <tr>
            <th width="1%">&nbsp;</th>
            <th width="20%">月份</th>
            <th width="20%">金额</th>
            <th width="59%"></th>
        </tr>

        <tr>
            <td></td>
            <td colspan="4" style="text-align:left;font-weight:bold;">支出</td>
        </tr>

        <?php
        $thisMonthOutSum = 0;
        foreach ($outList as $row) {
            $thisMonthOutSum += $row["sumOut"];
            ?>
            <TR id="content">
                <TD></TD>
                <TD class="to_left">
                    <a href="javascript:fGoto();"
                       onclick="ReportDetail.openByTimeRangeExcludeFilter('<?php echo $row["start"] ?>', '<?php echo $row["end"] ?>');"><?php echo $row["month"] ?></a>
                </TD>
                <TD class="number">
                    <?php echo number_format($row["sumOut"], 2, ".", "") ?>
                </TD>

                <TD></TD>
            </TR>
            <?php
        }

        $thisMonthOutAvg = $thisMonthOutSum/count($outList);
        ?>


        <TR id="content">
            <TD></TD>
            <TD class="to_left">支出小计</TD>
            <TD class="number"><?php echo number_format($thisMonthOutSum, 2, ".", "") ?></TD>
            <TD></TD>
            <TD class="number"></TD>
        </TR>


        <TR id="content">
            <TD></TD>
            <TD class="to_left">平均支出</TD>
            <TD class="number"><?php echo number_format($thisMonthOutAvg, 2, ".", "") ?></TD>
            <TD></TD>
            <TD class="number"></TD>
        </TR>
    </table>

    <?php
} else if ($method == "monthOut") {
    $dateFrom = isset($_POST["dateFrom"]) && $_POST["dateFrom"] ? strtotime($_POST["dateFrom"]) : strtotime("1970-01-01");
    $dateTo = isset($_POST["dateTo"]) && $_POST["dateTo"] ? strtotime($_POST["dateTo"]) : time();
    $tagIds = isset($_POST["tagId"]) ? trim($_POST["tagId"], ",") : "";
    $categoryId = isset($_POST["categoryId"]) ? $_POST["categoryId"] : null;
    $excludeMarks = isset($_POST["excludeMarks"]) ? trim($_POST["excludeMarks"], ",") : "";

    $thisMonthOut = $flowClass->findFlowsByTimeRangeExcludeFilter($userId,
        tally_flow::$INOUT_EXPENSE, $dateFrom, $dateTo, $tagIds, $categoryId, $excludeMarks);
    ?>
    <!--begin:数据列表-------------------------------------------------------------------------------------------------->
    <table id="reportDetailList" class="listtable" cellpadding="0" cellspacing="1">
        <thead>
        <tr>
            <th width="15%">发生日期</th>
            <th width="15%">类别</th>
            <th width="30%">标签</th>
            <th width="15%">金额</th>
            <th width="25%">说明</th>
        </tr>
        </thead>

        <tbody>
        <?php
        foreach($thisMonthOut as $flow) {
            $inout = "left";
            if ($flow["moneyOut"] > 0) {
                $inout = "right";
            }

            $flowType = "";
            if (tally_flow::$INOUT_TRANSFER != $flow["inOrOut"]) {
                $flowType = isset($flowTypeList[$flow["flowType"]]) ? $flowTypeList[$flow["flowType"]]["name"] : '';
            } else {
                $flowType = $accountList[$flow["transferTargetAccountId"]]["name"];
            }

            $bizType = 0;
            switch ($flow["inOrOut"]) {
                case tally_flow::$INOUT_INCOMME:
                    $bizType = 11;
                    break;
                case tally_flow::$INOUT_EXPENSE:
                    $bizType = 20;
                    break;
                default:
                    $bizType = 30;
                    break;

            }

            $tradeTime = strtotime($flow["tradeTime"]);
            $category = $tallyFlowTypeClass->findFlowTypeById($userId, $flow["flowType"]);
            $mark = "";
            $tagIdList = $flowClass->findTagByFlow($userId, $flow["id"]);
            if ($tagIdList) {
                $tags = "";
                foreach ($tagIdList as $tagMap) {
                    if ($tags) {
                        $tags .= ",";
                    }
                    $tags .= $tagList[$tagMap["tagId"]]["name"];
                }
                if ($tags) {
                    $mark .= "[" . $tags . "]";
                }
            }
            ?>
            <tr>
                <td>
                    <p title="<?php echo date("Y-m-d H:i", $tradeTime)?>">
                        <?php echo date("Y-m-d", $tradeTime)?>
                    </p>
                </td>
                <td>
                    <?php echo $category["name"]?>
                </td>
                <td>
                    <?php echo $mark?>
                </td>

                <td class="number">
                    <?php echo $flow["moneyIn"]>0?$flow["moneyIn"]:$flow["moneyOut"]?>
                </td>


                <td>
                    <?php echo $flow["desc"]?>
                </td>
            </tr>
            <?php
        }
        ?>

        </tbody>
    </table>

    <div class="buttons">
        <input type="button" class="button"  value="关闭" onclick="CM.close(this);return false;"/>
    </div>
    <!--end:数据列表区-------------------------------------------------------------------------------------------------->
<?php
} else if ($method == "pole") {
    // 所时间段每月收入与支出
    $dateFrom = isset($_POST["dateFrom"]) && $_POST["dateFrom"] ? strtotime($_POST["dateFrom"]) : strtotime("1970-01-01");
    $dateTo = isset($_POST["dateTo"]) && $_POST["dateTo"] ? strtotime($_POST["dateTo"]) : time();
    $tagIds = isset($_POST["tagId"]) ? trim($_POST["tagId"], ",") : "";
    $categoryId = isset($_POST["categoryId"]) ? $_POST["categoryId"] : null;

    $startTime = $dateFrom;
    $endTime = strtotime(date('Y-m-' . date('t', $startTime) . ' 23:59:59', $startTime));
    $categories = array();
    $outList = array();
    while ($startTime < $dateTo) {
        $thisMonthOut = $flowClass->getCountByTimeRangeExcludeFilter($userId,
            tally_flow::$INOUT_EXPENSE, $startTime, $endTime, $tagIds, $categoryId);
        $categories[] = date("n月", $startTime);
        $outList[] = abs($thisMonthOut);

        $startTime = $endTime + 1;
        $endTime = strtotime(date('Y-m-' . date('t', $startTime) . ' 23:59:59', $startTime));
    }

    echo json_encode(array(
        "categories" => $categories,
        "series" => array(
             array(
                "name" => '支出',
                "data" => $outList

            )
        ),
    ));
} else {
    $flowClass = new tally_flow();
    $flowList = $flowClass->findFlowByUserId($userId, 0, 0, "", "",
        "", "", 0, 0, "tradeTimeAsc", 0, 1);
    $firstTradeYear = date("Y", strtotime($flowList[0]["tradeTime"]));
    $currentYear = date("Y", time());
    $currentMonth = date("m", time());
    ?>
    <!-- begin:导航条 -->
    <div class="titlebar">
        <h3>
            按月储蓄统计
        </h3>
    </div>
    <!-- end:导航条 -->

    <div class="tab_wrapper">
        <div class="body">
            <!-- begin:搜索区 -->
            <form id="schForm" name="schForm" method="post">
                <div class="searchbar" id="searchbar" style="line-height: 150%; display: block;">
                    <div class="base_condition">
                        <table>
                            <tr>
                                <td>
                                    <SELECT id="dateSpan" NAME="dateSpan"
                                            onChange="updateDate('dateSpan','dateFrom','dateTo');">
                                        <option value="">日期</option>
                                        <option value="today">今日</option>
                                        <option value="theWeek">本周</option>
                                        <option value="theMonth">本月</option>
                                        <option value="theQuarter">本季度</option>
                                        <option value="theYear">今年</option>
                                        <option value="lastWeek">上周</option>
                                        <option value="lastMonth">上月</option>
                                        <option value="lastQuarter" selected>上季度</option>
                                        <option value="lastYear">去年</option>
                                        <option value="last7Day">近7天</option>
                                        <option value="last30Day">近30天</option>
                                        <option value="custom">自定义</option>
                                    </SELECT>
                                    从<INPUT class="Wdate date" TYPE="text" id="dateFrom" NAME="dateFrom"
                                            onFocus="WdatePicker();" value="" onChange="updateType('dateSpan');">
                                    至<INPUT class="Wdate date" TYPE="text" id="dateTo" NAME="dateTo"
                                            onFocus="WdatePicker();" value="" onChange="updateType('dateSpan');">
                                </td>
                                <td><input id="searchBtn" class="button" type="button" value="查询"
                                           onclick="MonthExpenseReport.search();Report.clearData();Report.searchChart();"/>
                                </td>
                            </tr>
                        </table>
                    </div>

                    <TABLE class="complex_condition">
                        <TR>
                            <td>
                                <label for="tags">
                                    排除的标签:
                                </label>

                                <?php
                                foreach ($excludeTags as $item) {
                                    ?>
                                    <span style="color: green"><?php echo $item["name"]; ?> </span>
                                    <?php
                                }
                                ?>

                                <input type="text" class="text rd" id="tags" name="tags"
                                       readonly="readonly" onClick="CM.clearValue(this);">
                                <input type="hidden" value="<?php echo join(",", $excludeTagIds); ?>" name="tagId"
                                       id="tagId"/>
                                <a title="选择项目" href="#"
                                   onclick="TagPicker.open(this,'1');return false;"><img src="/images/icons/select.gif"
                                                                                         align="absmiddle"/>
                                </a>
                            </td>

                            <TD>
                                <label for="categoryName">
                                    排除的支出类别:
                                </label>
                            </td>
                            <td colspan="10">

                                <?php
                                foreach ($excludeCategories as $item) {
                                    ?>
                                    <span style="color: green"><?php echo $item["name"]; ?> </span>
                                    <?php
                                }
                                ?>

                                <input type="hidden" id="categoryId" name="categoryId"
                                       value="<?php echo join(",", $excludeCategoryIds); ?>"/>
                                <input type="text" class="text rd" id="categoryName" name="categoryName"
                                       readonly="readonly" onClick="CM.clearValue(this);">
                                <a title="收支类别" href="#"
                                   onclick="CategoryPicker.open(this,'4');return false;"><img
                                            src="/images/icons/select.gif" align="absmiddle"/>
                                </a>
                            </TD>

                            <TD>
                                <label for="mark">
                                    排除的支出备注:
                                </label>
                            </td>
                            <td colspan="10">

                                <?php
                                foreach ($excludeMarks as $item) {
                                    ?>
                                    <span style="color: green"><?php echo $item; ?> </span>
                                    <?php
                                }
                                ?>

                                <input type="hidden" id="excludeMarks" name="excludeMarks"
                                       value="<?php echo join(",", $excludeMarks); ?>"/>
                            </TD>

                            <TD>
                                <INPUT TYPE="radio" NAME="flag" value="1" checked hidden>
                            </TD>

                        </tr>


                    </TABLE>

                </div>
            </form>
            <!-- end:搜索区 -->

            <div class="report_bar">
                <span>数据列表</span>
            </div>

            <div id="dataView" class="data">
                <div align="center">
                    <img align="absmiddle" src='/images/common/loading1.gif'>
                </div>
            </div>


            <div class="report_bar">
                <span>数据图表</span>
            </div>


            <div id="chartView" class="chartView">
                <div align="center">
                    <img align="absmiddle" src='/images/common/loading1.gif'>
                </div>
            </div>


            <!-- end:---------主数据区 -->
        </div>
    </div>


    <SCRIPT LANGUAGE="JavaScript">
        <!--
        $(document).ready(function () {
            updateDate('dateSpan', 'dateFrom', 'dateTo');
        });

        //-->
    </SCRIPT>
    <?php
}
?>
